<?php
namespace app\manage\controller;
use think\Db;
class ChannelAccount extends Base
{
    //列表
    public function index(){
        if( request()->isAjax() ){
            $page = input('page');
            $limit = input('limit');
            $channelId = input('channel_id');
            $plat = input('plat');

            $where['status'] = ['<>', -1];
            if(!empty($channelId)){
                $where = $channelId<5000 ? ['cps_id'=>$channelId] : ['channel_id'=>$channelId];
            }
            if(!empty($plat)){
                $where = $plat=='cps' ? ['channel_id'=>1000] : ['channel_id'=>['>=', 5000]];
            }

            if( ! $count=model('ViewChannel')->where($where)->count() ){
                $this->layTable();
            }

            $select = model('ViewChannel')
                ->where($where)
                ->order('add_time desc')
                ->limit(($page-1)*$limit, $limit)
                ->select();

            $data = [];
            $channelIdName = model('Channel')->channelIdName();
            $channelIdType = config('channel_type');

            foreach ($select as $k=>$v){
                $data[] = [
                    'channel_id' => $v['channel_id']==1000 ? 'CPS' : 'SDK',
                    'cps_id' => $v['channel_id']==1000 ? $v['cps_id'] : $v['channel_id'],
                    'cps_name' => $v['channel_id']==1000 ? $channelIdName[ $v['cps_id'] ] : $channelIdName[ $v['channel_id'] ],
                    'cps_type' => isset($channelIdType[ $v['cps_type'] ]) ? $channelIdType[ $v['cps_type'] ] : '',
                    'account' => $v['account'],
                    'pay_rate' => $v['pay_rate'],
                    'pid' => $v['pid'] ? $channelIdName[ $v['pid'] ] : '',
                    'add_time' => date('Y-m-d H:i:s', $v['add_time']),
                    'status' => $v['status'],
                ];
            }
            $this->layTable(0, '渠道列表', $data, $count);
        }else{
            return view();
        }
    }

    //添加
    public function add(){
        if( request()->isAjax() ){
            $cpsType = input('cps_type');
            $username = input('username');
            $account = input('account');
            $password = input('password');
            $passwordConfirm = input('password_confirm');
            $payRate = input('pay_rate');
            $sonNum = input('son_num');
            $intro = input('intro');

            if($cpsType==3){
                $channelId = model('ViewChannel')->max('channel_id');
                $channelId += 1;
                $sdk['channel_id'] = $channelId;
                $sdk['code'] = transPinyin($username) . rand(1000, 9999);
                $sdk['channel_name'] = $username;
                $sdk['type'] = 'sdk';
                $sdk['channel_code'] = $channelId;
                $sdk['intro'] = $intro;
                $sdk['status'] = 1;
                $sdk['pay_rate'] = $payRate;
                $sdk['account'] = $account;
                $sdk['password'] = md5($password);
                $sdk['password_confirm'] = md5($passwordConfirm);
                $sdk['add_time'] = time();
                $sdk['cps_type'] = $cpsType;

                $addRs = model('Channel')
                    ->validate([
                        'channel_name' => 'unique:channel',
                        'account' => 'unique:channel',
                        'password'=>'confirm'
                    ], [
                        'channel_name.unique' => 'SDK渠道名称已存在',
                        'account.unique' => 'SDK登录账号已存在',
                        'password.confirm' => 'SDK两次密码不一致'
                    ])->allowField(true)->save( $sdk );
            }else{
                $cps['channel_id'] = 1000;
                $cps['code'] = 'miyu';
                $cps['channel_name'] = 'miyu';
                $cpsId = model('ViewChannel')->where('cps_id', '<', 5000)->max('cps_id');
                $cpsId += 1;
                $cps['cps_id'] = $cpsId;
                $cps['cps_name'] = $username;
                $cps['type'] = 'cps';
                $cps['channel_code'] = $cpsId;
                $cps['intro'] = $intro;
                $cps['status'] = 1;
                $cps['pay_rate'] = $payRate;
                $cps['account'] = $account;
                $cps['password'] = md5($password);
                $cps['password_confirm'] = md5($passwordConfirm);
                $cps['cps_type'] = $cpsType;
                $cps['add_time'] = time();
                $cps['son_num'] = $sonNum;

                $addRs = model('Channel')
                    ->validate([
                        'cps_name' => 'unique:channel',
                        'account' => 'unique:channel',
                        'password'=>'confirm'
                    ], [
                        'cps_name.unique' => 'CPS渠道名称已存在',
                        'account.unique' => 'CPS登录账号已存在',
                        'password.confirm' => 'CPS两次密码不一致'
                    ])->allowField(true)->save( $cps );
            }

            del_dir(RUNTIME_PATH . 'temp');

            $addRs ? $this->layJson(0, '添加成功') : $this->layJson(1, model('Channel')->getError());
        }else{
            return view();
        }
    }

    //编辑
    public function edit(){
        if( request()->isAjax() ){
            $channelId = input('cps_id');
            $cpsType = input('cps_type');
            $username = input('username');
            $account = input('account');
            $password = input('password');
            $passwordConfirm = input('password_confirm');
            $sonNum = input('son_num');
            $intro = input('intro');
            $status = input('status');

            $where = $channelId<5000 ? ['cps_id'=>$channelId] : ['channel_id'=>$channelId];

            if(isset($status)){
                model('Channel')->isUpdate(true)->save(['status'=>$status], $where);
                $this->layJson(0, '编辑成功');
            }

            if($cpsType==3){
                $sdk['channel_name'] = $username;
                $sdk['intro'] = $intro;
                $sdk['account'] = $account;

                $whereUser['channel_id'] = ['<>', $channelId];
                $whereUser['cps_name'] = $username;
                if( model('Channel')->where($whereUser)->count() ){
                    $this->layJson(1, 'CPS渠道名称已存在');
                }

                $editRs = model('Channel')->allowField(true)->isUpdate(true)->save($sdk, $where);

                if(!empty($password)){
                    md5($password)!==md5($passwordConfirm) && $this->layJson(1, '两次密码不一致');
                    model('Channel')->save(['password'=>md5($password)], ['account'=>$account]);
                }
            }else{
                $cps['cps_name'] = $username;
                $cps['intro'] = $intro;
                $cps['son_num'] = $sonNum;

                $whereUser['cps_id'] = ['<>', $channelId];
                $whereUser['cps_name'] = $username;
                if( model('Channel')->where($whereUser)->count() ){
                    $this->layJson(1, 'CPS渠道名称已存在');
                }

                $editRs = model('Channel')->allowField(true)->isUpdate(true)->save($cps, $where);

                if(!empty($password)){
                    md5($password)!==md5($passwordConfirm) && $this->layJson(1, '两次密码不一致');
                    model('Channel')->save(['password'=>md5($password)], ['account'=>$account]);
                }
            }
            $editRs!==false ? $this->layJson(0, '编辑成功') : $this->layJson(1, model('Channel')->getError());
        }else{
            $channelId = input('cps_id');
            $where = $channelId<5000 ? ['cps_id'=>$channelId] : ['channel_id'=>$channelId];
            $find = model('Channel')->where($where)->find();
            if($find['channel_id']==1000){
                $find['username'] = $find['cps_name'];
            }else{
                $find['username'] = $find['channel_name'];
            }
            return view('', ['find'=>$find]);
        }
    }

    //删除
    public function del(){
        $channelId = input('cps_id');
        $where = $channelId<5000 ? ['cps_id'=>$channelId] : ['channel_id'=>$channelId];
        $delRs = model('Channel')->isUpdate(true)->save(['status'=>-1], $where);
        $delRs!==false ? $this->layJson(0, '删除成功') : $this->layJson(1, '删除失败，请重试');
    }

    //关联渠道
    public function relation(){
        if( request()->isAjax() ){
            $cpsId = input('cps_id');
            $channelId = input('channel_id');

            $cpsFind = model('ViewChannel')->field('account, password')->where('cps_id', $cpsId)->find();
            $sdkFind = model('ViewChannel')->field('account, password')->where('channel_id', $channelId)->find();

            if(!empty($cpsFind['account']) && empty($sdkFind['account'])){
                model('Channel')->save(['account'=>$cpsFind['account'], 'password'=>$cpsFind['password']], ['channel_id'=>$channelId]);
                $this->layJson(0, '成功关联CPS渠道');
            }else if(empty($cpsFind['account']) && !empty($sdkFind['account'])){
                model('Channel')->save(['account'=>$sdkFind['account'], 'password'=>$sdkFind['password']], ['cps_id'=>$cpsId]);
                $this->layJson(0, '成功关联联运渠道');
            }else if(empty($cpsFind['account']) && empty($sdkFind['account'])){
                $this->layJson(1, '两个渠道都没有账号，不能关联');
            }else{
                $this->layJson(1, '两个渠道有已经有账号，请联系管理员');
            }
        }else{
            $cpsId = model('ViewChannel')->where('channel_id', 1000)->order('cps_id desc')->select();
            $channelId = model('ViewChannel')->where('channel_id', '>=', 5000)->order('channel_id desc')->select();
            return view('', ['cps_id'=>$cpsId, 'channel_id'=>$channelId]);
        }
    }

    //限制礼包数量
    public function limit(){
        if( request()->isAjax() ){
            $cpsId = input('cps_id');
            $giveNum = input('give_num');

            foreach ($giveNum as $typeId=>$editNum){
                $where = ['cps_id'=>$cpsId, 'type_id'=>$typeId];
                if($editNum==''){
                    Db::name('channelBagNum')->where($where)->delete();
                    continue;
                }

                if( Db::name('ChannelBagNum')->where($where)->count() ){
                    Db::name('ChannelBagNum')->where($where)->update(['give_num'=>$editNum]);
                }else{
                    Db::name('ChannelBagNum')->insert(['give_num'=>$editNum, 'cps_id'=>$cpsId, 'type_id'=>$typeId]);
                }
            }
            $this->layJson(0, '编辑成功');
        }else{
            $select = model('ChannelBagType')->order('add_time desc')->select();

            foreach ($select as &$v){
                $whereNum['cps_id'] = input('get.cps_id');
                $whereNum['type_id'] = $v['id'];
                $giveNum = model('ChannelBagNum')->where($whereNum)->value('give_num');
                $v['give_num'] = isset($giveNum) ? $giveNum : '';
            }
            return view('', ['select'=>$select]);
        }
    }
}